using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;

public abstract class JoyStickBase : MonoBehaviour, IDragHandler, IPointerDownHandler, IPointerUpHandler
{
    [SerializeField] private Image JoyStickBackGround;
    [SerializeField] private Image JoyStickSosok;
    [SerializeField] private Image JoyStickArea;
    [SerializeField] private Camera CurrentCamera;

    private Vector2 JoystickStartPosotion;

    protected Vector2 InputVector;

    [SerializeField] private Color InActiveJoystick;
    [SerializeField] private Color ActiveJoystick;

    private bool JoystickIsActive = false;
    private void Start() 
    {
        ClickEffectHide();

        JoystickStartPosotion = JoyStickBackGround.rectTransform.anchoredPosition;
           
    }

    public void OnDrag(PointerEventData eventData)
    {
        Vector2 JoyStickPosition;
        if(RectTransformUtility.ScreenPointToLocalPointInRectangle(JoyStickBackGround.rectTransform, eventData.position, CurrentCamera,out JoyStickPosition))
        {
            JoyStickPosition.x = (JoyStickPosition.x * 2 / JoyStickBackGround.rectTransform.sizeDelta.x);
            JoyStickPosition.y = (JoyStickPosition.y * 2 / JoyStickBackGround.rectTransform.sizeDelta.y);

            InputVector = new Vector2(JoyStickPosition.x, JoyStickPosition.y);
            InputVector = (InputVector.magnitude > 1f) ? InputVector.normalized : InputVector;

            JoyStickSosok.rectTransform.anchoredPosition = new Vector2(InputVector.x * (JoyStickBackGround.rectTransform.sizeDelta.x / 2), InputVector.y * (JoyStickBackGround.rectTransform.sizeDelta.y / 2));
        }
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        ClickEffectShow();
        Vector2 JoystickBackgroundPosition; 

        if(RectTransformUtility.ScreenPointToLocalPointInRectangle(JoyStickArea.rectTransform, eventData.position, CurrentCamera, out JoystickBackgroundPosition))
        {
            JoyStickBackGround.rectTransform.anchoredPosition = new Vector2(JoystickBackgroundPosition.x, JoystickBackgroundPosition.y);
        }

    }

    private void ClickEffectShow()
    {
        JoyStickBackGround.color = ActiveJoystick;
        JoyStickSosok.color = ActiveJoystick;
    }
    private void ClickEffectHide()
    {
        JoyStickBackGround.color = InActiveJoystick;
        JoyStickSosok.color = InActiveJoystick;
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        JoyStickBackGround.rectTransform.anchoredPosition = JoystickStartPosotion;
        ClickEffectHide();

        InputVector =Vector2.zero;
        JoyStickSosok.rectTransform.anchoredPosition = Vector2.zero;
    }
}
